package com.ruoyi.project.oms.paeaRiskItem.service.impl;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.PaeaUserRole;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExportUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.er.domain.PaeaErError;
import com.ruoyi.project.er.enums.PaeaErrorSource;
import com.ruoyi.project.er.mapper.PaeaErErrorMapper;
import com.ruoyi.project.er.service.IPaeaErErrorRegisterService;
import com.ruoyi.project.oms.paeaAuAuditGroupUserRel.domain.PaeaAuAuditGroupUserRel;
import com.ruoyi.project.oms.paeaAuAuditGroupUserRel.mapper.PaeaAuAuditGroupUserRelMapper;
import com.ruoyi.project.oms.paeaAuAuditDetailfifldInfo.domain.PaeaAuAuditDetailfifldInfo;
import com.ruoyi.project.oms.paeaAuAuditDetailfifldInfo.mapper.PaeaAuAuditDetailfifldInfoMapper;
import com.ruoyi.project.oms.paeaAuAuditFifldInfo.domain.PaeaAuAuditFifldInfo;
import com.ruoyi.project.oms.paeaAuAuditFifldInfo.mapper.PaeaAuAuditFifldInfoMapper;
import com.ruoyi.project.oms.paeaAuTaskAssignManner.domain.PaeaAuTaskAssignManner;
import com.ruoyi.project.oms.paeaAuTaskAssignManner.mapper.PaeaAuTaskAssignMannerMapper;
import com.ruoyi.project.oms.paeaAuType.domain.PaeaAuType;
import com.ruoyi.project.oms.paeaAuType.mapper.PaeaAuTypeMapper;
import com.ruoyi.project.oms.paeaRiskItem.domain.PaeaRiskItemNumModel;
import com.ruoyi.project.oms.paeaRiskItem.domain.PaeaRiskItemQuery;
import com.ruoyi.project.oms.paeaRiskItemDetail.domain.PaeaRiskItemDetail;
import com.ruoyi.project.oms.paeaRiskItemDetail.mapper.PaeaRiskItemDetailMapper;
import com.ruoyi.project.paea.paeaDsTrade.domain.PaeaDsTrade;
import com.ruoyi.project.paea.paeaDsTrade.mapper.PaeaDsTradeMapper;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.tool.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.oms.paeaRiskItem.mapper.PaeaRiskItemMapper;
import com.ruoyi.project.oms.paeaRiskItem.domain.PaeaRiskItem;
import com.ruoyi.project.oms.paeaRiskItem.service.IPaeaRiskItemService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.ui.ModelMap;

/**
 * 预警Service业务层处理
 *
 * @author gang.wei
 * @date 2020-03-22
 */
@Service
public class PaeaRiskItemServiceImpl extends ServiceImpl<PaeaRiskItemMapper, PaeaRiskItem> implements IPaeaRiskItemService
{
    @Autowired
    private PaeaRiskItemMapper paeaRiskItemMapper;
    @Autowired
    private PaeaRiskItemDetailMapper paeaRiskItemDetailMapper;
    @Autowired
    private PaeaAuAuditGroupUserRelMapper paeaAuAuditGroupUserRelMapper;
    @Autowired
    private PaeaAuTypeMapper paeaAuTypeMapper;
    @Autowired
    private PaeaAuTaskAssignMannerMapper paeaAuTaskAssignMannerMapper;
    @Autowired
    private PaeaAuAuditFifldInfoMapper paeaAuAuditFifldInfoMapper;
    @Autowired
    private PaeaAuAuditDetailfifldInfoMapper paeaAuAuditDetailfifldInfoMapper ;
    @Autowired
    private PaeaDsTradeMapper paeaDsTradeMapper;
    @Autowired
    private PaeaErErrorMapper paeaErErrorMapper;
    @Autowired
    private IPaeaErErrorRegisterService paeaErErrorRegisterService;
    /**
     * 查询预警
     *
     * @param id 预警ID
     * @return 预警
     */
    @Override
    public PaeaRiskItem selectPaeaRiskItemById(String id)
    {
        return paeaRiskItemMapper.selectPaeaRiskItemById(id);
    }

    /**
     * 查询预警列表
     *
     * @param paeaRiskItem 预警
     * @return 预警
     */
    @Override
    public List<PaeaRiskItem> selectPaeaRiskItemList(PaeaRiskItem paeaRiskItem)
    {
        return paeaRiskItemMapper.selectPaeaRiskItemList(paeaRiskItem);
    }

    /**
     * 新增预警
     *
     * @param paeaRiskItem 预警
     * @return 结果
     */
    @Override
    public int insertPaeaRiskItem(PaeaRiskItem paeaRiskItem)
    {
        return paeaRiskItemMapper.insertPaeaRiskItem(paeaRiskItem);
    }

    /**
     * 修改预警
     *
     * @param paeaRiskItem 预警
     * @return 结果
     */
    @Override
    public int updatePaeaRiskItem(PaeaRiskItem paeaRiskItem)
    {
        return paeaRiskItemMapper.updatePaeaRiskItem(paeaRiskItem);
    }

    /**
     * 删除预警对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deletePaeaRiskItemByIds(String ids)
    {
        return paeaRiskItemMapper.deletePaeaRiskItemByIds(Convert.toStrArray(ids));
    }
    /**
     * 批量查询预警
     *
     * @param ids 需要查询的数据ID
     * @return 结果
     */
    @Override
    public List<PaeaRiskItem> selectPaeaRiskItemByIds(String ids)
    {
        return paeaRiskItemMapper.selectPaeaRiskItemByIds(Convert.toStrArray(ids));
    }
    @Override
    public List<PaeaRiskItem> selectPaeaRiskItemsByInfoId(String riskInfoId)
    {
        return paeaRiskItemMapper.selectPaeaRiskItemsByInfoId(riskInfoId);
    }
    @Override
    public List<PaeaRiskItem> selectPaeaRiskItemsByInfoIdAndBe(String riskInfoId)
    {
        return paeaRiskItemMapper.selectPaeaRiskItemsByInfoIdAndBe(riskInfoId);
    }
    /**
     * 初始化预警信息
     */
    public void init(ModelMap mmap){
        List<PaeaAuType> paeaAuTypes = paeaAuTypeMapper.queryRiskType();
        User user = ShiroUtils.getSysUser();
        List<Role> roles = user.getRoles();
        for(Role role:roles){
            if(PaeaUserRole.监控中心条线风险预警员.getRoleCode().equals(role.getRoleId())){
                List<PaeaAuType> paeaAuTypeList1 = paeaAuTypeMapper.findAuTypeByUserCode(user.getLoginName());
                if(paeaAuTypeList1!=null&&paeaAuTypeList1.size()>0){
                    paeaAuTypes = paeaAuTypeList1;
                }
                break;
            }
        }
        mmap.put("paeaAuTypes", paeaAuTypes);
        String impType = paeaAuTypes.size()>0?paeaAuTypes.get(0).getCode():"";
        mmap.put("impType",impType);
        List<PaeaRiskItemNumModel> paeaRiskItemNumModels = this.getPaeaRiskItemNumModel(user,null,null,null,null);
        mmap.put("paeaRiskItemNumModels",paeaRiskItemNumModels);
        mmap.put("errorSource",PaeaErrorSource.S风险预警.getValue());
        //Integer scope = 30;
        //scope = LimitScope.getSetLimitDays(LimitScope.预警日期.getCode(), serviceParameterSettingImpl);
    }
    //监督数量
    @Override
    public List<PaeaRiskItemNumModel> getPaeaRiskItemNumModel(User user, String beginDate, String endDate, String brCode, String impType){
        List<Role> roles = user.getRoles();
        String filterFlag = "1";
        for(Role role:roles){
            if(PaeaUserRole.监管主管.getRoleCode().equals(role.getRoleId())||
                    PaeaUserRole.监管员.getRoleCode().equals(role.getRoleId())||
                    PaeaUserRole.系统管理员.getRoleCode().equals(role.getRoleId())){
                filterFlag = "";
            }
        }
        return paeaRiskItemMapper.getPaeaRiskItemNumModel(user.getLoginName(), beginDate, endDate, brCode, impType, filterFlag);
    }

    @Override
    public List<PaeaRiskItemDetail> queryPaeaRiskItemDetail(PaeaRiskItemDetail paeaRiskItemDetail){
        QueryWrapper wrapper = new QueryWrapper<PaeaRiskItemDetail>();
        if(StringUtils.isNotEmpty(paeaRiskItemDetail.getRelId())){wrapper.eq("rel_id",paeaRiskItemDetail.getRelId());}
        if(paeaRiskItemDetail.getDataDate()!=null){wrapper.eq("data_Date",paeaRiskItemDetail.getDataDate());}
        if(paeaRiskItemDetail.getImpType()!=null){wrapper.eq("imp_type",paeaRiskItemDetail.getImpType());}
        List<PaeaRiskItemDetail> paeaRiskItemDetails = paeaRiskItemDetailMapper.selectList(wrapper);
        return paeaRiskItemDetails;
    }

    //监督数量JSON
    @Override
    public String getPaeaRiskItemNumModelJson(PaeaRiskItemQuery paeaRiskItemQuery) {
        User user = ShiroUtils.getSysUser();
        String beginDate = paeaRiskItemQuery.getStartTrDate()==null?"":DateUtils.parseDateToStr("yyyy-MM-dd",paeaRiskItemQuery.getStartTrDate());
        String endDate = paeaRiskItemQuery.getEndTrDate()==null?"":DateUtils.parseDateToStr("yyyy-MM-dd",paeaRiskItemQuery.getEndTrDate());
        String brCode = paeaRiskItemQuery.getBrCode();
        String impType = paeaRiskItemQuery.getImpType();
        List<PaeaRiskItemNumModel> paeaRiskItemNumModels = this.getPaeaRiskItemNumModel(user,beginDate, endDate, brCode, impType);
        String js =  JSONArray.toJSONString(paeaRiskItemNumModels);
        return js;
    }
    /**
     * 删除预警信息
     *
     * @param id 预警ID
     * @return 结果
     */
    @Override
    public int deletePaeaRiskItemById(String id)
    {
        return paeaRiskItemMapper.deletePaeaRiskItemById(id);
    }
    /**
     * 查询预警列表
     *
     * @param paeaRiskItem 预警
     * @return 预警
     */
    @Override
    public List<PaeaRiskItem> queryRiskItem(PaeaRiskItemQuery paeaRiskItem, List<PaeaAuAuditFifldInfo> paeaAuAuditFifldInfos,String goupCode) {

        String title = "ID,STATUS,IMP_TYPE,AU_OPER,BATCH_ID,REL_ID,ERR_ID,DATA_DATE";
        for (PaeaAuAuditFifldInfo auditFifldInfoinfo :paeaAuAuditFifldInfos){
            String code = auditFifldInfoinfo.getCode();
            if(!("STATUS".equals(code)||"IMP_TYPE".equals(code)||"BATCH_ID".equals(code)||"REL_ID".equals(code)||"ERR_ID".equals(code))){
                title +=","+auditFifldInfoinfo.getCode();
            }
        }
        QueryWrapper wrapperitem = new QueryWrapper<PaeaRiskItem>();
        wrapperitem.select(title);
        if(null!=paeaRiskItem.getStartTrDate() && null==paeaRiskItem.getEndTrDate()){
            paeaRiskItem.setEndTrDate(paeaRiskItem.getStartTrDate());
        }else if(null!=paeaRiskItem.getStartTrDate() && null!=paeaRiskItem.getEndTrDate()){
            wrapperitem.between("tr_date",paeaRiskItem.getStartTrDate(),paeaRiskItem.getEndTrDate());
        }
        if(StringUtils.isNotEmpty(goupCode)){
            wrapperitem.eq("audit_Code",goupCode);
        }
        if(StringUtils.isNotEmpty(paeaRiskItem.getImpType())){
            wrapperitem.eq("imp_Type",paeaRiskItem.getImpType());
        }
        if(StringUtils.isNotEmpty(paeaRiskItem.getBrCode())){
            wrapperitem.eq("br_code",paeaRiskItem.getBrCode());
        }
        if(paeaRiskItem.getStatus()!=null){
            wrapperitem.eq("status",paeaRiskItem.getStatus());
        }
        wrapperitem.orderByAsc("status");
        wrapperitem.orderByAsc("tr_Date");
        List<PaeaRiskItem> paeaRiskItems = paeaRiskItemMapper.selectList(wrapperitem);
        return paeaRiskItems;
    }
    public List<PaeaRiskItem> queryRiskItems(PaeaRiskItemQuery paeaRiskItem) {
        User user = ShiroUtils.getSysUser();
        String groupCode = this.isByGroup(user);
        QueryWrapper wrapperitem = new QueryWrapper<PaeaRiskItem>();
        if(null!=paeaRiskItem.getStartTrDate() && null==paeaRiskItem.getEndTrDate()){
            paeaRiskItem.setEndTrDate(paeaRiskItem.getStartTrDate());
        }else if(null!=paeaRiskItem.getStartTrDate() && null!=paeaRiskItem.getEndTrDate()){
            wrapperitem.between("tr_date",paeaRiskItem.getStartTrDate(),paeaRiskItem.getEndTrDate());
        }
        if(StringUtils.isNotEmpty(groupCode)){
            wrapperitem.eq("audit_Code",groupCode);
        }
        if(StringUtils.isNotEmpty(paeaRiskItem.getImpType())){
            wrapperitem.eq("imp_Type",paeaRiskItem.getImpType());
        }
        if(StringUtils.isNotEmpty(paeaRiskItem.getBrCode())){
            wrapperitem.eq("br_code",paeaRiskItem.getBrCode());
        }
        if(paeaRiskItem.getStatus()!=null){
            wrapperitem.eq("status",paeaRiskItem.getStatus());
        }
        wrapperitem.orderByAsc("status");
        wrapperitem.orderByAsc("tr_Date");
        List<PaeaRiskItem> paeaRiskItems = paeaRiskItemMapper.selectList(wrapperitem);
        return paeaRiskItems;
    }
    @Override
    public String getAuditFifldInfoJson(String impType) {
        //表头字段
        QueryWrapper wrapper = new QueryWrapper<PaeaAuAuditFifldInfo>();
        wrapper.eq("imp_type",impType);
        wrapper.orderByAsc("display_seq");
        List<PaeaAuAuditFifldInfo> paeaAuAuditFifldInfos = paeaAuAuditFifldInfoMapper.selectList(wrapper);
        /*for(PaeaAuAuditFifldInfo info:paeaAuAuditFifldInfos){
            String field = info.getCode().toLowerCase();
            if(field.indexOf("_")>0){
                if(field.length()>=field.indexOf("_")+3){
                    field = field.substring(0,field.indexOf("_"))+field.substring(field.indexOf("_")+1,field.indexOf("_")+2).toUpperCase()+field.substring(field.indexOf("_")+2);
                }else{
                    field = field.substring(0,field.indexOf("_"))+field.substring(field.indexOf("_")+1,field.indexOf("_")+2).toUpperCase();
                }
            }
            info.setCode(field);
        }*/
        String js =  JSONArray.toJSONString(paeaAuAuditFifldInfos);
        return js;
    }
    @Override
    public String getAuditDetailFifldInfoJson(String impType) {
        //表头字段
        QueryWrapper wrapper = new QueryWrapper<PaeaAuAuditDetailfifldInfo>();
        wrapper.eq("imp_type",impType);
        wrapper.orderByAsc("display_seq");
        List<PaeaAuAuditDetailfifldInfo> paeaAuAuditFifldInfos = paeaAuAuditDetailfifldInfoMapper.selectList(wrapper);
        String js =  JSONArray.toJSONString(paeaAuAuditFifldInfos);
        return js;
    }
    @Override
    public AjaxResult getRegisteErrInfo(String riskId) {
        PaeaRiskItem item = paeaRiskItemMapper.selectPaeaRiskItemById(riskId);
        //检查是否创建过差错
        if(item==null){
            return AjaxResult.warn("未查询到预警信息！");
        }
        QueryWrapper wrapper = new QueryWrapper<PaeaErError>();
        if(item.getTrDate()!=null){wrapper.eq("tr_date",item.getTrDate());}
        if(StringUtils.isNotEmpty(item.getImpType())){wrapper.eq("au_type_id",item.getImpType());}
        wrapper.eq("audit_item_id",item.getId());
        PaeaErError error = paeaErErrorMapper.selectOne(wrapper);
        if(item.getStatus()==3||error!=null){
            return AjaxResult.warn("该笔预警已创建差错，请核对！");
        }
        int errorSource = PaeaErrorSource.S风险预警.getValue();
        String vchFlag = "0";
        String manFlag = "0";
        Date trDate = item.getTrDate();
        String trDateStr = "";
        String orgId = StringUtils.isEmpty(item.getBrCode())?"":item.getBrCode();
        String tellerId = StringUtils.isEmpty(item.getTrTelr())?"":item.getTrTelr();
        String vchNo = StringUtils.isEmpty(item.getVchNo())?"":item.getVchNo();
        String tradeId="";
        String auTypeId = StringUtils.isEmpty(item.getImpType())?"":item.getImpType();
        String auditItemId = StringUtils.isEmpty(item.getId())?"":item.getId();
        if(trDate!=null){
            trDateStr = DateUtils.parseDateToStr("yyyy-MM-dd",trDate);
        }
        if(vchNo!=null && trDate!=null){
            //查询流水
            PaeaDsTrade paeaDsTrade = paeaDsTradeMapper.selectOne(new QueryWrapper<PaeaDsTrade>().eq("tr_date",trDate).eq("vch_no",vchNo).eq("filter_flag",1));
            if(paeaDsTrade!=null){
                tradeId = paeaDsTrade.getId();
                vchFlag = "1";
            }
        }
        String errInfo = errorSource+"@"+vchFlag+"@"+manFlag+"@"+trDateStr+"@"+orgId+"@"+tellerId+"@"+vchNo+"@"+tradeId+"@"+auTypeId+"@"+auditItemId;
        return AjaxResult.success(errInfo);
    }

    @Override
    public String exportItem(PaeaRiskItemQuery paeaRiskItemQuery) {
        //获取表头
        String impType = paeaRiskItemQuery.getImpType()==null?"":paeaRiskItemQuery.getImpType();
        List<PaeaAuAuditFifldInfo> fieldInfos = this.getAuAuditFifldInfo(impType);
        //小组
        User user = ShiroUtils.getSysUser();
        String groupCode = this.isByGroup(user);
        List<PaeaRiskItem> list = this.queryRiskItem(paeaRiskItemQuery,fieldInfos,groupCode);
        Map<String,String> headMap = new LinkedHashMap<String,String>();
        boolean statusFiled =  false;
        for(PaeaAuAuditFifldInfo inf:fieldInfos){
            String field = inf.getEntityCode();
            headMap.put(field,inf.getName());
            if("STATUS".equals(inf.getCode())){
                statusFiled = true;
            }
        }
        if(!statusFiled){
            headMap.put("status","状态");
        }
        JSONArray ja = new JSONArray();
        ja.addAll(list);
        String filename = UUID.randomUUID().toString() + "_风险预警.xlsx";
        OutputStream out = null;
        try {
            out = new FileOutputStream(new ExportUtils().getAbsoluteFile(filename));
        }catch (Exception e){
            throw new BusinessException("导出Excel失败，请联系网站管理员！");
        }
        String title = "预警日期";
        if(paeaRiskItemQuery.getStartTrDate()!=null){
            title += DateUtils.parseDateToStr("yyyyMMdd",paeaRiskItemQuery.getStartTrDate());
        }
        if(paeaRiskItemQuery.getEndTrDate()!=null){
            title += "至"+DateUtils.parseDateToStr("yyyyMMdd",paeaRiskItemQuery.getEndTrDate());
        }
        List<PaeaAuType> paeaAuTypes = this.selectPaeaAuTypesByCode(impType);
        title += " 预警项 "+paeaAuTypes.get(0).getName();
        ExportUtils.exportExcelX(title,headMap,ja,null,0,out);//downloadExcelFile
        return filename;
    }

    @Override
    public String exportBatch(PaeaRiskItemQuery paeaRiskItemQuery) {
        return null;
    }

    /*@Override
    public String exportBatch(PaeaRiskItemQuery paeaRiskItemQuery) {
        //小组
        User user = ShiroUtils.getSysUser();
        String groupCode = this.isByGroup(user);
        List<PaeaRiskInfo> list = this.queryRiskInfo(paeaRiskItemQuery,groupCode);
        Map<String,String> headMap = new LinkedHashMap<String,String>();
        headMap.put("trDate","交易日期");
        headMap.put("brCode","机构号");
        headMap.put("accNo","账号/客户号/开户行/柜员");
        headMap.put("custName","客户名/开户行名");
        headMap.put("impName","预警规则");
        headMap.put("itemCount","笔数");
        headMap.put("normalCount","确认正常笔数");
        headMap.put("errCount","确认差错笔数");
        headMap.put("status","状态");
        JSONArray ja = new JSONArray();
        ja.addAll(list);
        String filename = UUID.randomUUID().toString() + "_风险预警批次.xlsx";
        OutputStream out = null;
        try {
            out = new FileOutputStream(new ExportUtils().getAbsoluteFile(filename));
        }catch (Exception e){
            throw new BusinessException("导出Excel失败，请联系网站管理员！");
        }
        String title = "预警日期";
        if(paeaRiskItemQuery.getStartTrDate()!=null){
            title += DateUtils.parseDateToStr("yyyyMMdd",paeaRiskItemQuery.getStartTrDate());
        }
        if(paeaRiskItemQuery.getEndTrDate()!=null){
            title += "至"+DateUtils.parseDateToStr("yyyyMMdd",paeaRiskItemQuery.getEndTrDate());
        }
        List<PaeaAuType> paeaAuTypes = this.selectPaeaAuTypesByCode(paeaRiskItemQuery.getImpType());
        title += " 预警项 "+paeaAuTypes.get(0).getName();
        ExportUtils.exportExcelX(title,headMap,ja,null,0,out);//downloadExcelFile
        return filename;
    }*/
    public String isByGroup(User user){
        PaeaAuTaskAssignManner paeaAuTaskAssignManner = paeaAuTaskAssignMannerMapper.selectOne(new QueryWrapper<>(new PaeaAuTaskAssignManner()).eq("manner","group"));
        if (null != paeaAuTaskAssignManner) {
            List<PaeaAuAuditGroupUserRel> auditGroups = paeaAuAuditGroupUserRelMapper.findAuditGroupByUserId(user.getLoginName());
            PaeaAuAuditGroupUserRel paeaAuAuditGroupUserRel =null;
            if(null!=auditGroups && auditGroups.size()>0){
                paeaAuAuditGroupUserRel =(PaeaAuAuditGroupUserRel) auditGroups.get(0);
            }
            return paeaAuAuditGroupUserRel ==null?null: paeaAuAuditGroupUserRel.getGroupId();
        }
        return null;
    }
    /**
     * 通过code查询监督类表
     * @param
     * @param
     * @return 监督类型集合
     */
    public List<PaeaAuType> selectPaeaAuTypesByCode(String code){
        return paeaAuTypeMapper.selectPaeaAuTypesByCode(code);
    }

    @Override
    public List<PaeaAuAuditFifldInfo> getAuAuditFifldInfo(String impType) {
        //表头字段
        QueryWrapper wrapper = new QueryWrapper<PaeaAuAuditFifldInfo>();
        wrapper.eq("imp_type",impType);
        wrapper.orderByAsc("display_seq");
        System.out.println("------------------------sql:"+wrapper.getSqlSelect());
        return  paeaAuAuditFifldInfoMapper.selectList(wrapper);
    }
    @Override
    public List<PaeaAuType> getPaeaAuType() {
        //所有预警项列表
        User user = ShiroUtils.getSysUser();
        List<PaeaAuType> paeaAuTypeList = paeaAuTypeMapper.queryRiskType();
        List<Role> roles = user.getRoles();
        for(Role role:roles){
            if(PaeaUserRole.监控中心条线风险预警员.getRoleCode().equals(role.getRoleId())){
                List<PaeaAuType> paeaAuTypeList1 = paeaAuTypeMapper.findAuTypeByUserCode(user.getLoginName());
                if(paeaAuTypeList1!=null&&paeaAuTypeList1.size()>0){
                    paeaAuTypeList = paeaAuTypeList1;
                }
                break;
            }
        }
        return paeaAuTypeList;
    }

    @Override
    public AjaxResult doConfirm(String id) {
        //查询paeaRiskInfo
        int result = 0;
        PaeaRiskItem paeaRiskItem = paeaRiskItemMapper.selectPaeaRiskItemById(id);
        if(paeaRiskItem==null){
            return  AjaxResult.error("未查到数据");
        }else if(paeaRiskItem.getStatus()==3){
            return AjaxResult.warn("已创建风险");
        }else if(paeaRiskItem.getStatus()==2){
            return AjaxResult.warn("已确认正常");
        }
        User user = ShiroUtils.getSysUser();
        paeaRiskItem.setStatus(new Integer(2));
        paeaRiskItem.setAuOper(user.getLoginName());
        paeaRiskItem.setAuDate(DateUtils.getNowDate());
        result =paeaRiskItemMapper.updatePaeaRiskItem(paeaRiskItem);
        return AjaxResult.success("提交成功");
    }

    @Override
    public AjaxResult doConfirmBatch(PaeaRiskItemQuery paeaRiskItemQuery,String ids) {
        User user = ShiroUtils.getSysUser();
        List<PaeaRiskItem> paeaRiskItems = null;
        if(StringUtils.isNotEmpty(ids)){
            paeaRiskItems = paeaRiskItemMapper.selectPaeaRiskItemByIds(Convert.toStrArray(ids));
        }else{
            paeaRiskItems =  this.queryRiskItems(paeaRiskItemQuery);
        }
        boolean result = false;
        int normCount = 0;
        for(PaeaRiskItem paeaRiskItem:paeaRiskItems){
            if(paeaRiskItem.getStatus()==1){//未监控
                paeaRiskItem.setStatus(new Integer(2));
                paeaRiskItem.setAuOper(user.getLoginName());
                paeaRiskItem.setAuDate(DateUtils.getNowDate());
                result = true;
                normCount+=1;
            }
        }
        if(result){
            return this.saveOrUpdateBatch(paeaRiskItems)?AjaxResult.success("批量提交成功!提交笔数："+normCount):AjaxResult.error("批量提交失败");
        }else{
            return AjaxResult.warn("没有需要批量提交的数据");
        }
    }
    //单笔下发回调更新
    @Override
    public AjaxResult registerErrorUpItem(String itemId) {
        User user = ShiroUtils.getSysUser();
        PaeaRiskItem paeaRiskItem = paeaRiskItemMapper.selectPaeaRiskItemById(itemId);
        //检查是否创建过差错
        if(paeaRiskItem==null){
            return AjaxResult.warn("未查询到预警信息！");
        }
        QueryWrapper wrapper = new QueryWrapper<PaeaErError>();
        if(paeaRiskItem.getTrDate()!=null){
            wrapper.eq("tr_date",paeaRiskItem.getTrDate());
        }
        if(StringUtils.isNotEmpty(paeaRiskItem.getImpType())){
            wrapper.eq("au_type_id",paeaRiskItem.getImpType());
        }
        wrapper.eq("audit_item_id",paeaRiskItem.getId());
        PaeaErError error = paeaErErrorMapper.selectOne(wrapper);
        if(error==null){
            return AjaxResult.warn("未创建差错！");
        }
        int status = 0;
        if(paeaRiskItem.getStatus()==1||paeaRiskItem.getStatus()==2){//未下发
            status = paeaRiskItem.getStatus();
            //添加工作量 预警+督办
            //servicePaeaReportBusinessImpl.savePaeaReportBusiness(userinfo,new java.util.Date(), 0, 0, 0, 0, paeaRiskItems.size(), 0, 0, paeaRiskItems.size(),0);
            //更新预警信息
            paeaRiskItem.setStatus(new Integer(3));
            paeaRiskItem.setAuOper(user.getLoginName());
            paeaRiskItem.setAuDate(DateUtils.getNowDate());
            paeaRiskItem.setErrId(error.getId()!=null?error.getId():"");
        }
        return this.saveOrUpdate(paeaRiskItem)?AjaxResult.success(status+"下发预警单成功!"):AjaxResult.error("下发预警单失败");
    }
    //批量下发
    @Override
    public AjaxResult addRiskBatch(PaeaRiskItemQuery paeaRiskItemQuery,String ids,String auditSuggest,String paeaErPoints) {
        User user = ShiroUtils.getSysUser();
        List<PaeaRiskItem> paeaRiskItems = null;
        if(StringUtils.isNotEmpty(ids)){
            paeaRiskItems = paeaRiskItemMapper.selectPaeaRiskItemByIds(Convert.toStrArray(ids));
        }else{
            paeaRiskItems =  this.queryRiskItems(paeaRiskItemQuery);
        }
        boolean result = false;
        int errCount = 0;
        for(PaeaRiskItem paeaRiskItem:paeaRiskItems){
            if(paeaRiskItem.getStatus()==1||paeaRiskItem.getStatus()==2){//未下发
                //创建差错
                PaeaErError paeaErError = this.createError(paeaRiskItem);
                paeaErError.setAuditSuggest(auditSuggest);
                paeaErError.setPaeaErPointIds(StringUtils.isNotEmpty(paeaErPoints)?Arrays.asList(paeaErPoints.split(",")):new ArrayList<String>());
                paeaErErrorRegisterService.registerError(paeaErError);
                errCount+=1;
                //添加工作量 预警+督办
                //servicePaeaReportBusinessImpl.savePaeaReportBusiness(userinfo,new java.util.Date(), 0, 0, 0, 0, paeaRiskItems.size(), 0, 0, paeaRiskItems.size(),0);
                //更新预警信息
                paeaRiskItem.setStatus(new Integer(3));
                paeaRiskItem.setAuOper(user.getLoginName());
                paeaRiskItem.setAuDate(DateUtils.getNowDate());
                paeaRiskItem.setErrId(paeaErError.getId()!=null?paeaErError.getId():"");
                result = true;
            }
        }
        if(result){
            return this.saveOrUpdateBatch(paeaRiskItems)?AjaxResult.success("批量下发预警单成功!批量下发笔数:"+errCount):AjaxResult.error("批量下发失败");
        }else{
            return AjaxResult.warn("没有需要下发的数据");
        }
    }
    private PaeaErError createError(PaeaRiskItem paeaRiskItem){
        int errorSource = PaeaErrorSource.S风险预警.getValue();
        String vchFlag = "0";
        String manFlag = "0";
        Date trDate = paeaRiskItem.getTrDate();
        String trDateStr = "";
        String orgId = StringUtils.isEmpty(paeaRiskItem.getBrCode())?"":paeaRiskItem.getBrCode();
        String tellerId = StringUtils.isEmpty(paeaRiskItem.getTrTelr())?"":paeaRiskItem.getTrTelr();
        String vchNo = StringUtils.isEmpty(paeaRiskItem.getVchNo())?"":paeaRiskItem.getVchNo();
        String tradeId="";
        String auTypeId = StringUtils.isEmpty(paeaRiskItem.getImpType())?"":paeaRiskItem.getImpType();
        String auditItemId = StringUtils.isEmpty(paeaRiskItem.getId())?"":paeaRiskItem.getId();
        if(trDate!=null){
            trDateStr = DateUtils.parseDateToStr("yyyy-MM-dd",trDate);
        }
        if(vchNo!=null && trDate!=null){
            //查询流水
            PaeaDsTrade paeaDsTrade = paeaDsTradeMapper.selectOne(new QueryWrapper<PaeaDsTrade>().eq("tr_date",trDate).eq("vch_no",vchNo).eq("filter_flag",1));
            if(paeaDsTrade!=null){
                tradeId = paeaDsTrade.getId();
                vchFlag = "1";
            }
        }
        PaeaErError paeaErError = new PaeaErError();
        paeaErError.setErrSource(errorSource);
        paeaErError.setTrDate(DateTimeUtil.parseSqlDate(trDateStr,DateTimeUtil.FMT_YY_MM_DD));
        paeaErError.setOrgId(orgId);
        paeaErError.setTellerId(tellerId);
        paeaErError.setVchNo(vchNo);
        paeaErError.setTradeId(tradeId);//待定
        paeaErError.setAuditItemId(auditItemId);
        paeaErError.setAuTypeId(auTypeId);
        paeaErError.setAuditProceeding(this.setAuditProceeding(paeaRiskItem));
        paeaErError.setAuditSuggest("");//TODO
        return paeaErError;
    }
    //监督详情-AJAX调用
    @Override
    public AjaxResult getAuditProceeding(PaeaRiskItem paeaRiskItem) {
        return AjaxResult.success(this.setAuditProceeding(paeaRiskItem));
    }
    //监督详情
    public String setAuditProceeding(PaeaRiskItem paeaRiskItem){
        List<PaeaAuAuditFifldInfo> paeaAuAuditFifldInfos = this.getAuAuditFifldInfo(paeaRiskItem.getImpType());
        StringBuffer auditProceed=new StringBuffer("");
        try {
            Class c =paeaRiskItem.getClass();
            for(PaeaAuAuditFifldInfo paeaAuAuditFifldInfo:paeaAuAuditFifldInfos){
                auditProceed.append(paeaAuAuditFifldInfo.getName()+":");
                String method = paeaAuAuditFifldInfo.getEntityCode().substring(0,1).toUpperCase()+paeaAuAuditFifldInfo.getEntityCode().substring(1);
                Method m1 = c.getDeclaredMethod("get"+method);
                Object obj = m1.invoke(paeaRiskItem);
                auditProceed.append(obj==null?"":obj.toString()+",");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return auditProceed.toString().endsWith(",")?auditProceed.toString().substring(0,auditProceed.toString().length()-1):auditProceed.toString();
    }
}
